package com.example.pets.view.activity;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.pets.R;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.pets.model.entities.Pet;
import com.example.pets.model.entities.dao.UserDao;
import com.example.pets.model.entities.database.AppDatabase;
import com.example.pets.model.entities.database.ShareprefenseUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.utils.MediaUtils;

import java.io.File;
import java.util.List;

public class EditDogProfileActivity extends AppCompatActivity {

    private ImageView ivDogAvatar;
    private Button btnChangeAvatar, btnSubmit;
    private EditText etNickname, etDescription, etBreed, etAge;
    private Spinner spType;
    private RadioGroup rgGender;
    private RadioButton rbMale, rbFemale;

    private Uri selectedImageUri = null; // 存储选中的图片 URI
    private String imagePath="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_dog_profile);
        AppDatabase.getDatabase(this).userDao();
        // 初始化控件
        ivDogAvatar = findViewById(R.id.iv_dog_avatar);
        btnChangeAvatar = findViewById(R.id.btn_change_avatar);
        etNickname = findViewById(R.id.et_nickname);
        etDescription = findViewById(R.id.et_description);
        spType = findViewById(R.id.sp_type);
        etBreed = findViewById(R.id.et_breed);
        rgGender = findViewById(R.id.rg_gender);
        rbMale = findViewById(R.id.rb_male);
        rbFemale = findViewById(R.id.rb_female);
        etAge = findViewById(R.id.et_age);
        btnSubmit = findViewById(R.id.btn_submit);

        // 点击更换头像
        btnChangeAvatar.setOnClickListener(v -> openGallery());

        // 提交按钮点击事件
        btnSubmit.setOnClickListener(v -> submitData());
    }

    private void openGallery() {

        PictureSelector.create(EditDogProfileActivity.this)
                .openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(1)
                .setImageEngine(new YImageEngine())
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 获取选择的图片结果
                    List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                    if (!selectList.isEmpty()) {
                        imagePath = selectList.get(0).getPath();
                        updateProfileImage(imagePath);
                    }
                    break;
            }
        }
    }
    private void updateProfileImage(String imagePath) {
        Glide.with(this)
                .load(imagePath)
                .into(ivDogAvatar);
    }
    private void submitData() {
        String nickname = etNickname.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        String breed = etBreed.getText().toString().trim();
        String ageStr = etAge.getText().toString().trim();

        int gender = rbMale.isChecked() ? 0 : (rbFemale.isChecked() ? 1 : -1);
        int type = spType.getSelectedItemPosition(); // 0=犬, 1=猫, 2=其他

        if (nickname.isEmpty()) {
            Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }

        if (gender == -1) {
            Toast.makeText(this, "请选择性别", Toast.LENGTH_SHORT).show();
            return;
        }

        if (ageStr.isEmpty()) {
            Toast.makeText(this, "请输入年龄", Toast.LENGTH_SHORT).show();
            return;
        }

        int age = Integer.parseInt(ageStr);
        long uid = ShareprefenseUtil.getinstanse().getLoginUser().getUid();
        Pet pet =new Pet();
        pet.setBirth(age+"");
        pet.setBreed(breed);
        pet.setGender(gender==0?true:false);
        pet.setOwner(uid);
        pet.setPname(nickname);
        pet.setImageUrl(imagePath);
        pet.setCreateTime("");
        new Thread(new Runnable() {
            @Override
            public void run() {
                long ids = AppDatabase.getDatabase(EditDogProfileActivity.this).petDao().insert(pet);
                if(ids>0){
                    finish();
                }
            }
        }).start();

        // 模拟提交数据（你可以替换为网络请求或数据库更新）
         Toast.makeText(this, "保存成功：" + nickname + ", " + breed + ", " + age, Toast.LENGTH_SHORT).show();

    }
}